Telegram Group & Telegram Channel
🔍 Как валидировать входные данные

Проверять данные вручную через if-ы — больно, скучно и не масштабируется.
Bean Validation (javax.validation) позволяет валидировать красиво и декларативно, не превращая код в болото.

1️⃣ Добавляем зависимости

implementation("org.springframework.boot:spring-boot-starter-validation")

ИЛИ

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>


2️⃣ Аннотации в DTO
public class UserRequest {

@NotBlank(message = "Имя не должно быть пустым")
private String name;

@Email(message = "Некорректный email")
private String email;

@Min(value = 18, message = "Возраст должен быть 18+")
private int age;

// геттеры и сеттеры
}


3️⃣ Включаем валидацию в контроллере
@PostMapping("/users")
public ResponseEntity<?> createUser(@Valid @RequestBody UserRequest request) {
userService.save(request);
return ResponseEntity.ok().build();
}


Без @Valid перед DTO ничего не сработает.

4️⃣ Глобальный обработчик ошибок
@RestControllerAdvice
public class ExceptionHandlerController {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleValidationErrors(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(err -> err.getField() + ": " + err.getDefaultMessage())
.toList();

return ResponseEntity.badRequest().body(errors);
}
}


Теперь ошибки приходят красиво и читаемо в JSON.

5️⃣ Кастомные валидаторы

Если нужно что-то особенное — например, проверка страны:
@Constraint(validatedBy = CountryValidator.class)
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidCountry {
String message() default "Страна не поддерживается";
}

public class CountryValidator implements ConstraintValidator<ValidCountry, String> {
private final List<String> allowed = List.of("RU", "US", "DE");

public boolean isValid(String value, ConstraintValidatorContext ctx) {
return allowed.contains(value);
}
}


💬 Всё ещё пишете if (dto.getName() == null)?

🐸 Библиотека джависта #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/javaproglib/6552
Create:
Last Update:

🔍 Как валидировать входные данные

Проверять данные вручную через if-ы — больно, скучно и не масштабируется.
Bean Validation (javax.validation) позволяет валидировать красиво и декларативно, не превращая код в болото.

1️⃣ Добавляем зависимости

implementation("org.springframework.boot:spring-boot-starter-validation")

ИЛИ

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>


2️⃣ Аннотации в DTO
public class UserRequest {

@NotBlank(message = "Имя не должно быть пустым")
private String name;

@Email(message = "Некорректный email")
private String email;

@Min(value = 18, message = "Возраст должен быть 18+")
private int age;

// геттеры и сеттеры
}


3️⃣ Включаем валидацию в контроллере
@PostMapping("/users")
public ResponseEntity<?> createUser(@Valid @RequestBody UserRequest request) {
userService.save(request);
return ResponseEntity.ok().build();
}


Без @Valid перед DTO ничего не сработает.

4️⃣ Глобальный обработчик ошибок
@RestControllerAdvice
public class ExceptionHandlerController {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleValidationErrors(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(err -> err.getField() + ": " + err.getDefaultMessage())
.toList();

return ResponseEntity.badRequest().body(errors);
}
}


Теперь ошибки приходят красиво и читаемо в JSON.

5️⃣ Кастомные валидаторы

Если нужно что-то особенное — например, проверка страны:
@Constraint(validatedBy = CountryValidator.class)
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidCountry {
String message() default "Страна не поддерживается";
}

public class CountryValidator implements ConstraintValidator<ValidCountry, String> {
private final List<String> allowed = List.of("RU", "US", "DE");

public boolean isValid(String value, ConstraintValidatorContext ctx) {
return allowed.contains(value);
}
}


💬 Всё ещё пишете if (dto.getName() == null)?

🐸 Библиотека джависта #буст

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tg-me.com/javaproglib/6552

View MORE
Open in Telegram


Библиотека джависта | Java Spring Maven Hibernate Telegram | DID YOU KNOW?

Date: |

How to Buy Bitcoin?

Most people buy Bitcoin via exchanges, such as Coinbase. Exchanges allow you to buy, sell and hold cryptocurrency, and setting up an account is similar to opening a brokerage account—you’ll need to verify your identity and provide some kind of funding source, such as a bank account or debit card. Major exchanges include Coinbase, Kraken, and Gemini. You can also buy Bitcoin at a broker like Robinhood. Regardless of where you buy your Bitcoin, you’ll need a digital wallet in which to store it. This might be what’s called a hot wallet or a cold wallet. A hot wallet (also called an online wallet) is stored by an exchange or a provider in the cloud. Providers of online wallets include Exodus, Electrum and Mycelium. A cold wallet (or mobile wallet) is an offline device used to store Bitcoin and is not connected to the Internet. Some mobile wallet options include Trezor and Ledger.

Export WhatsApp stickers to Telegram on iPhone

You can’t. What you can do, though, is use WhatsApp’s and Telegram’s web platforms to transfer stickers. It’s easy, but might take a while.Open WhatsApp in your browser, find a sticker you like in a chat, and right-click on it to save it as an image. The file won’t be a picture, though—it’s a webpage and will have a .webp extension. Don’t be scared, this is the way. Repeat this step to save as many stickers as you want.Then, open Telegram in your browser and go into your Saved messages chat. Just as you’d share a file with a friend, click the Share file button on the bottom left of the chat window (it looks like a dog-eared paper), and select the .webp files you downloaded. Click Open and you’ll see your stickers in your Saved messages chat. This is now your sticker depository. To use them, forward them as you would a message from one chat to the other: by clicking or long-pressing on the sticker, and then choosing Forward.

Библиотека джависта | Java Spring Maven Hibernate from id


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM USA